require 'zdc.doc'
require 'zsvc.que'
require 'zsvc.packet'
require 'zsvc.evhandle'
local monutil=require 'zsvc.monutil'
module(..., package.seeall)

local Appcon= {}
zsvc.evhandle.InitEvent(Appcon)
local Appcon_mt = {__metatable = {}, __index = Appcon}


function new(params)
	local obj = setmetatable({mon=params.mon,appaddr=params.appaddr,react=params.react,apps=params.apps,clis=params.clis,logger=params.logger,que=zsvc.que.new(),sp=zsvc.packet.new(),rp=zsvc.packet.new()}, Appcon_mt)
	obj.name='Appcon'
	obj.authed=false
	obj:OnClose()
	obj.logger:info('Appcon start for ' .. logging.tostring(obj.appaddr))
	return obj
end

function Appcon:GetBusy()
	return self.que:Count()
end
function Appcon:cb_conn_ready()
		self.connwait=nil
		self.logger:info('Appcon has connect to ' .. logging.tostring(self.appaddr))
		monutil.mon_start(self)
		self.apps:AddOne(self.appaddr.appid,self)
end
function Appcon:OnClose()
	self.que:Clear() --TODO: reconnected and send left pkt
	if self.fd then
		self:_bv_close()
		self.logger:warn('Appcon close fd for ' .. logging.tostring(self.appaddr))
		monutil.mon_broke(self)
		self.fd:close()
	end
	self.fd=nil
	self.connwait=nil
	self.apps:DelOne(self.appaddr.appid,self)
	self:_bv_init_connect(self.appaddr.host,self.appaddr.port)
end

function Appcon:OnMsg(packet)
	return self.clis:OnRespond(packet)
end

